package tgc.edu.ljc.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import tgc.edu.ljc.custom.CommonService;
import tgc.edu.ljc.entity.Course;
import tgc.edu.ljc.entity.Grade;
import tgc.edu.ljc.entity.Stu;
import tgc.edu.ljc.repository.CourseRepository;
import tgc.edu.ljc.repository.GradeRepository;
import tgc.edu.ljc.repository.StudentRepository;
@Service
public class GradeService extends CommonService<Grade, Integer>{
	@Autowired
	private GradeRepository gradeDAO;
	@Autowired
	private StudentRepository studentDAO;
	@Autowired
	private CourseRepository courseDAO;
	
	public Page<Grade> findByIdIsNull(Pageable pageable) {
		return gradeDAO.findByIdIsNull( pageable);
	}

	public Page<Grade> findByClassIdAndCourseId(Integer classId, Integer courseId, Pageable pageable) {
		Course course=courseDAO.findById(courseId).get();
		List<Stu> students=studentDAO.findByTbClassId(classId);
		for (Stu stu : students) {
			Grade model=gradeDAO.findByStuIdAndCourseId(stu.getId(),courseId);
			if(model==null) {
				model=new Grade();
				model.setStu(stu);
				model.setCourse(course);
				save(model);
			}
		}
		Page<Grade> page=gradeDAO.findByStuTbClassIdAndCourseId(classId,courseId,pageable);
		return page;
	}

	public Page<Grade> findByStuId(Integer stuId, Pageable pageable) {
		Stu stu=studentDAO.findById(stuId).get();
		Integer classId=stu.getTbClass().getId();
		List<Course> courses = gradeDAO.findCoursesByClassId(classId);
		for (Course course : courses) {
			Grade model=gradeDAO.findByStuIdAndCourseId(stuId, course.getId());
			if(model==null) {
				model=new Grade();
				model.setStu(stu);
				model.setCourse(course);
				save(model);
			}
		}
		return gradeDAO.findByStuId(stuId, pageable);
	}

	public List<Grade> findByStuId(Integer studentId) {
		return gradeDAO.findByStuId(studentId);
	}

	public List<Course> findCoursesByClassId(Integer classId) {
		return gradeDAO.findCoursesByClassId(classId);
	}

	public Grade findByStuIdAndCourseId(Integer stuId, Integer courseId) {
		return gradeDAO.findByStuIdAndCourseId(stuId,courseId);
		
	}

}
